/**
 * Base64 ---> Blob
 * @param { Base64 } urlData 
 * @param { String } type 
 */
export function imageBase64ToBlob (urlData, type='image/jpeg') {
  try {
    var arr = urlData.split(',');
    var mine = arr[0].match(/:(.*?);/)[1] || type;
    var bytes = window.atob(arr[1]);
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);

    for(var i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }

    return new Blob([ab], {
      type: mine
    });
  } catch (e) {
    var ab = new ArrayBuffer(0);
    return new Blob([ab], { type: type })
  }
}

/**
 * Blob转本地URL
 * @param { Blob } blobData 
 */
export function bolbToUrl (blobData) {
  return window.URL.createObjectURL(blobData)
}

/**
 * blob转base64
 * @param { blob } blobData 
 * @param { Funciton } cb 
 */
export function blobToBase64 (blobData, cb) {
  let reader = new FileReader()
  reader.onload = (e) => {
    cb && cb(e.target.result)
  }
  reader.readAsDataURL(blobData)
}

/**
 * url转blob
 * @param { String } url 
 */
export function urlToBlob (url) {
  return new Promise(resolve => {
    let xhr = new XMLHttpRequest()
    xhr.open('get', url, true)
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response)
      }
    }
    xhr.responseType = 'blob'
    xhr.send()
  })
}